<?php
/**
 * 支付回调类
 */
namespace App\Controller\Index;

use Common\Model\OrderLogModel;
use Common\Model\OrderModel;
use Common\Model\OrderProductModel;
use Common\Model\QuanfanModel;
use Common\Model\TarentoCashFlowModel;
use Think\Controller;
use Think\Alipay;
use Think\Wxpay\Wxpush;

class NotifyController extends Controller{
    /**
     * 支付宝回调
     */
    public function index(){

        require_once(CORE_PATH."Alipay/alipay.config.php");
        require_once(CORE_PATH."Alipay/lib/alipay_notify.class.php");

        //计算得出通知验证结果
        $alipayNotify = new Alipay\App\Driver\AlipayNotify();
        $verify_result = $alipayNotify->verifyNotify();
        //if($verify_result) {//验证成功
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代


            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——

            //获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表

            //商户订单号

            $out_trade_no = $_POST['out_trade_no'];

            //支付宝交易号

            $trade_no = $_POST['trade_no'];

            //交易状态
            $trade_status = $_POST['trade_status'];


            if($_POST['trade_status'] == 'TRADE_FINISHED') {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知

                //调试用，写文本函数记录程序运行情况是否正常
                //logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
            }
            else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
                //判断该笔订单是否在商户网站中已经做过处理
                $model = new OrderModel();
                $re = $model->where("order_id='$out_trade_no'")->field("status,pay_status,stock_shop,member_id,order_type,ms_id,ship_addr,ship_name,cost,cpns_price,freight,ms_Freight_risk,total_ms_taxation,cash_price")->find();

                $pay_status=$re['pay_status'];
                $is_succeed=$re['status'];
                $stock_shop=$re['stock_shop'];
                $member_id=$re['member_id'];
                $order_type=$re['order_type'];
                $belondShopId = $re['ms_id'];
                $cash_price = $re['cash_price'];
                //单笔支付商品金额
                $oneOrderCost = $re['cost'];
                //支付总金额
                $allMoney = $re['cost'] + $re['cpns_price'] + $re['freight'] + $re['ms_Freight_risk'] + $re['total_ms_taxation'];
                $tcf_model = new TarentoCashFlowModel();
                $tcf_data['member_id'] = $member_id;
                $tcf_data['price'] = -$cash_price;
                $tcf_data['type_code'] = 'SET_ORDER';
                $tcf_data['description'] = "下单支付，订单号：$out_trade_no";
                $tcf_data['extension'] = $out_trade_no;
                $tcf_data['create_time'] = date('Y-m-d H:i:s',time());
                $tcf_model->add($tcf_data);

                if($is_succeed==1)//如果验证成功,并且流水表中的记录为新提交
                {
                    if ($pay_status == 1)//如果是支付订单的情况
                    {
                        //查看是否有多订单
                        $orderModel = new OrderModel();
                        $orderModel->order_see($out_trade_no);

                    }
                    //处理库存的
                    $model = new OrderProductModel();
                    $re = $model->join("left join haiou_product_sku as b on a.product_id=b.id")->where("a.order_id='$out_trade_no'")->field("a.product_id,a.num as nums,a.microstock_num,a.price,a.member_id,a.active_id,b.stock_relations")->select();
                    // 获取全返活动的产品ID集合
                    $commonOrderTotal = 0;

                    foreach ($re as $val) {
//
                        $commonOrderTotal += $val['price'] * $val['nums'];
                    }
                    //查询用户是否使用优惠券结算
                    $model = new OrderModel();
                    $strs = $model->where("order_id='$out_trade_no'")->find();
                    if ($strs['cpns_price'] > 0) {
                        $commonOrderTotal = $commonOrderTotal - $strs['cpns_price'];
//
                    }

                    // 查看是否是第一单
                    $model = new OrderModel();
                    $orderNum = $model->where("status>1 and pay_status>1 and active_id != 3 and member_id=$member_id and master_order_id=''")->field("COUNT(member_id) AS total_num")->find();
                    $orderNum = $orderNum['total_num'];
                    file_put_contents('/www/web_api/test1.txt',$orderNum);

                    // 如果购买了普通区产品，并且是第一单，则可以参与99返活动
                    if ($commonOrderTotal > 0 && $orderNum['total_num'] <= 1) {
                        $quanfanOrderData = [
                            'memberId' => $member_id,
                            'orderId' => $out_trade_no,
                            'shopId' => $belondShopId,
                            'orderType' => 2,
                            'price' => $commonOrderTotal
                        ];

                        // TODO: test
                        $env = 'produce';
                        $model = new OrderLogModel();
                        $model->add(['order_id'=>$out_trade_no,'admin_id'=>'','admin_name'=>'','text'=>"testxxxx:{$env}commonOrderTotal",'behavior'=>'付款','result'=>'success']);
                        // 添加全返订单
                        $model = new QuanfanModel();
                        $model->addOrder($quanfanOrderData);
                    }

                        if ($order_type < 3) {//微店订单不参与合伙人结算
                            //放入返利处理队列
                           // include_once("$config[webroot]/lib/Httpsqs.php");
                           // Httpsqs::put('tarentoOrder', array('order_id' => $out_trade_no));
                        } else {

                            // TODO: test
                            $env = 'produce';
                            $model = new OrderLogModel();
                            $model->add(['order_id'=>$out_trade_no,'admin_id'=>'','admin_name'=>'','text'=>'payment_class.php 610-line','behavior'=>'付款','result'=>'success']);

                            //给用户推送消息
                            $replaceArr = [];
                            //订单商品信息
                            $model = new OrderProductModel();
                            $productName = $model->where("order_id='$out_trade_no'")->field("product_name")->find();
                            $productName = $productName['product_name'];

                            //查询订单支付总金额

                            $param = [
                                'memberId' => $re['member_id'],
                                'orderProductPrice' => $allMoney,
                                'orderProductName' => $productName,
                                'orderAddress' => $re['ship_name'] . ',' . $re['ship_addr'],
                                'orderName' => $out_trade_no,
                                'url' => 'http://wx.52ywy.com/?shop=' . $re['ms_id'] . '#&cart/orderdetail/?id=' . $out_trade_no
                            ];
                            $Wxpush = new Wxpush();
                            $message = $Wxpush->getMessageDetail('orderPaySuccess', $replaceArr, $param);

                            if(!empty($message)){//调用接口
                                $param['first'] = $message['subject'];
                                $param['remark'] = $message['message'];

                                //$result = Api::callItemApi('Weixin', 'msgPush', ["memberId"=>$param['memberId'],"msgType"=>$flag,"msgJson"=>json_encode($param)]);

                                $result = $Wxpush->msgPush($param['memberId'], 'orderPaySuccess', json_encode($param));
                                //写日志
                                $data['param'] = ["memberId"=>$param['memberId'],"msgType"=>'orderPaySuccess',"msgInfo"=>$param];
                                $data['result'] = $result;
                                $datas = json_encode($data,JSON_UNESCAPED_UNICODE);
                                $datas = @mysql_escape_string($datas);
                                $modes_log = new OrderLogModel();
                                $modes_log->add(['type'=>'PUSH_WX_MSG','data'=>$datas,'status'=>1]);
                            }

                        }

                    }
                }

            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

            echo "success";		//请不要修改或删除

            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
       // }
        //else {
            //验证失败
            //echo "fail";

            //调试用，写文本函数记录程序运行情况是否正常
            //logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
        //}
    }
}